<template>
  <el-card class="box-card">
    <div slot="header" class="clearfix">
      <span>基本资料</span>
    </div>
    <div class="text item">
      <el-form label-width="80px" :rules="userRules" :model="userInfo" ref="form">
        <el-form-item label="登录用户">
          <el-input disabled :value="userInfo.username"></el-input>
        </el-form-item>
        <el-form-item label="用户昵称" prop="nickname">
          <el-input v-model="userInfo.nickname"></el-input>
        </el-form-item>
        <el-form-item label="用户邮箱" prop="email">
          <el-input v-model="userInfo.email"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="updateUser">确认修改</el-button>
          <el-button @click="reset">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
  </el-card>
</template>

<script>
import { updateUserAPI } from '@/api/user'
export default {
  name: 'UserInfo',
  data() {
    return {
      // 繁琐
      // userInfo: {
      //   id: this.$store.state.user.user.id,
      //   nickname: this.$store.state.user.user.nickname,
      //   email: this.$store.state.user.user.email
      // }
      userInfo: { ...this.$store.state.user.user },
      userRules: {
        nickname: [
          { required: true, message: '昵称必填', trigger: 'blur' },
          { min: 2, max: 10, message: '昵称长度2~10位', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '邮箱必填', trigger: 'blur' },
          { type: 'email', message: '邮箱格式不正确', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    // 配合上面繁琐得方法
    // async updateUser() {
    //   const { data: res } = await updateUserAPI(this.userInfo)
    //   if (res.code === 0) {
    //     this.$store.dispatch('user/getUserInfo')
    //     this.$message.success(res.message)
    //   }
    // },
    updateUser() {
      this.$refs.form.validate(async valid => {
        if (!valid) return
        const { data: res } = await updateUserAPI({
          id: this.userInfo.id,
          nickname: this.userInfo.nickname,
          email: this.userInfo.email
        })
        if (res.code === 0) {
          // this.$store.commit('user/getUser', this.userInfo)
          this.$store.dispatch('user/getUserInfo')
          this.$message.success(res.message)
        } else {
          this.$message.error(res.message)
        }
      })
    },
    reset() {
      // resetFields 回复表单成为最初的样子，并去掉表单验证
      this.$refs.form.resetFields()
      // 将vuex中的数据再回填到组件中
      this.userInfo = { ...this.$store.state.user.user }
    }
  }
}
</script>

<style lang="less" scoped>
.el-form {
  width: 400px;
}
</style>
